#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/6/17 23:40
# @Author : cjw
"""文件操作"""
from os.path import exists
from yaml import safe_load_all, safe_load


class FileBase:

    def __init__(self, file_path: str):
        if not exists(file_path):
            raise FileNotFoundError(f'找不到文件：{file_path}')
        self._file_path = file_path
        self._data = None


class YmlOperator(FileBase):
    """yml文件操作"""

    def __init__(self, yml_path: str, multi: bool = False):
        """
        :param yml_path: yml文件路径
        :param multi: 是否多节读取，yml文件通过'---'符号进行多节处理
        """
        super(YmlOperator, self).__init__(yml_path)
        self._multi = multi

    @property
    def data(self):
        # 第一次获取数据时，才进行读取
        if not self._data:
            with open(self._file_path, encoding='utf-8') as fp:
                if self._multi:
                    self._data = list(safe_load_all(fp))
                else:
                    self._data = safe_load(fp)
        return self._data


if __name__ == '__main__':
    yml = YmlOperator('../datas/calc_add.yml')
    print(yml.data)
